<template>
	<view class="uni-container uni-pa-4">
		<!-- <view><view class='uni-section-header__decoration line'></view>车架号</view> -->
		<!-- <uni-section title="车架号" type="line" padding="0px"> -->


		<view class="part-box">
			<uni-section title="车架号" type="line" padding="0px">
				<view class="zgj-car-container" @click="onvinclick">
					<view class="zgj-vin-big">
						<text v-if="!hasVin">点击上传17位车架号照片</text>
						<view class="zgj-vin-has" v-else>
							<image :src="vinImg" class="vinimg"></image>
							<view class="zgj-brand">
								<text>{{ vin }}</text>
								<text>{{ brand ? brand.cn_name : '' }}</text>
							</view>
						</view>
					</view>
				</view>
			</uni-section>

			<view class="zgj-goodstype-container">
				<uni-section title="品质要求" type="line" padding="0px">
					<checkbox-group @change="onQualityChange">
						<label v-for="goodsType of goodsTypes" :key="goodsType.value" class="zgj-goodstype">
							<checkbox :value="goodsType.value" :checked="goodsType.checked" color="#C4171E">
								{{ goodsType.name }}</checkbox>
						</label>
					</checkbox-group>
				</uni-section>
			</view>

			<uni-section title="配件要求" type="line" padding="0px">
				<view class="zgj-part-container">
					<textarea class="zgj-part-input " placeholder="请描述配件需求，支持语音输入。" v-model="requirements"></textarea>
					<zgj-sound v-if="showRecord" :remove="hasRequirements" class="uni-im-sound" @success="sendSound"
						@remove="removeSound"></zgj-sound>
				</view>
			</uni-section>
			<zgj-voice :info="voiceInfo" v-if="hasVoice"></zgj-voice>
			<view class="zgj-part-image-container">
				<uni-file-picker limit="5" title="旧件、铭牌、清单照片（可选）" v-model="images"></uni-file-picker>
			</view>
		</view>

		<view class="foot-btns">
			<view class='shuomin' @tap.stop="openDescription()">
				查看说明
			</view>
			<view class="phone" @tap.stop="onorder()">
				一键询价 多家报价
			</view>
		</view>


		<!-- <button  style="margin-top: 30px;display: inline-block; background-color: rgb(245,245,245);width:35%;margin-right:1%" @tap="onorder">查看说明</button> 
		<button type="primary" style="margin-top: 30px; display: inline-block;ackground-color: #C4171E;width:64%" @tap="onorder">一键询价 多家报价</button> -->

		<!-- vin popup -->
		<uni-popup ref="vinpopup" type="top" :mask-click="false">
			<view class="zgj-popup-content">
				<text class="zgj-margin-bottom" style="font-size: 17px;">车架号识别</text>
				<fy-poster :url="vinImg"></fy-poster>
				<input class="uni-input zgj-vin uni-my-4" maxlength="17" placeholder-style="color:#F76260"
					:placeholder="phVin" v-model="vinResult.vin" @input="onVinInput" />
				<view class="zgj-vin-brands zgj-margin-bottom">
					<view class="vechile-brand">
						<image :src="brandLogo" class="brand"></image>
						<text v-if="hasBrand">{{ brand ? brand.cn_name : '' }}</text>
						<text v-else style="color:#F76260">请选择品牌</text>
					</view>
					<view><button size="mini" @click="onbrand">手动选品牌</button></view>
				</view>
				<view class="zgj-vin-brands">
					<button size="mini" @click="onvincancel">重新上传</button>
					<button type="primary" size="mini" @click="onvinconfirm">结果确认</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import {
	store,
	mutations
} from '@/uni_modules/uni-id-pages/common/store.js'
import fyPoster from '../../components/fy-poster/poster.vue'
const goodsTypes = [{
	value: "1",
	name: "原厂",
	checked: true
}, {
	value: "2",
	name: "品牌",
	checked: true
}, {
	value: "3",
	name: "拆车",
	checked: true
}, {
	value: "4",
	name: "其他",
	checked: false
}]
const app = getApp()
export default {
	data() {
		return {
			registed: false,
			goodsTypes: goodsTypes,
			requirements: '',
			showRecord: true,
			hasVin: false,
			hasVoice: false,
			vinImg: '',
			vin: '',
			phVin: '',
			brand: {
				cn_name: null,
                id:null,
			},
			photos: [],
			images: [],
			vinResult: {
				vin: '',
				vinImg: ''
			},
			voiceInfo: null,
			qualityString: "1,2,3,4"
		}
	},
	components: {
		fyPoster
	},
	computed: {
		hasRequirements() {
			return this.hasVoice || this.requirements.trim().length > 0
		},
		userInfo() {
			return store.userInfo
		},
		isSigned() {
			return this.userInfo && !!this.userInfo._id
		},
		brandLogo() {
			if (this.brand && this.brand.images) {
				let brandImages = JSON.parse(this.brand.images)
				if (brandImages && brandImages.length > 0) {
					return 'https://images.51zuhuobao.com/images/' + brandImages[0]
				}
			}
			return 'https://cheche.oss-cn-beijing.aliyuncs.com/web/zhb_nullbg%402x.jpg'
		},
		hasBrand() {
			return this.showRecord || this.brand
		}

	},
	onHide() {
		this.resetPageData()
		// 页面隐藏
	},
	onShow() {
		const params = app.globalData.enquiryParams; //获取分享参数
		if (params) {
			if(params.vin){
			this.setOptions(params)
			}
			if (!uni.getStorageSync('uni_id_token')) {
				uni.showModal({
					title: "提示",
					content: '您还没有登录，请先登录',
					success(resturn) {
						if (resturn.confirm) {
							mutations.logout()
							if(params.images){
							uni.setStorageSync('cyt', JSON.stringify(params))
							}
						} 
					},
				});
			}
		}
		uni.removeStorageSync('enquiryParams')
		app.globalData.enquiryParams = null;
		if (uni.getStorageSync('cyt')) {
			const storedObjectStr = uni.getStorageSync('cyt');
			const storedObject = JSON.parse(storedObjectStr);
			this.setOptions(storedObject, true)
		}
		var brand = uni.getStorageSync("brand")
		if (brand) {
			this.brand = brand
			uni.removeStorage({
				key: "brand"
			})
		}

		console.log('enquiry show', app.globalData.signing, app.globalData.registing, this.isSigned, this.registed,
		this.userInfo, this.userInfo.mobile, this.brand)
		this.checkShopInfo()
	},
	onLoad(options) {
		if (options.scene) {
			let scene = decodeURIComponent(options.scene)
			let arr = scene.split('=')
			if (arr.length === 2 && arr[0] === 'p') {
				this.$config.promotor = arr[1]
			}
		}
		if (this.isSigned && !app.globalData.signing) {
			console.log("onload")
			this.checkRegist()
		}
	},
	onShareAppMessage(res) {
		return {
			title: '我的车车找个件快速询价', // 分享的标题
			path: '/pages/enquiry/enquiry', // 分享路径，可以包含查询参数
			success: function () {
				// 转发成功后的回调函数
				console.log('转发成功');
			},
			fail: function (err) {
				// 转发失败后的回调函数
				console.log('转发失败', err);
			}
		}
	},
	onShareTimeline(res) {
		return {
			title: '我的车车找个件快速询价', // 分享的标题
			path: '/pages/enquiry/enquiry', // 分享路径，可以包含查询参数
			success: function () {
				// 转发成功后的回调函数
				console.log('转发成功');
			},
			fail: function (err) {
				// 转发失败后的回调函数
				console.log('转发失败', err);
			}
		}
	},
	methods: {
		resetPageData() {
			this.goodsTypes = goodsTypes
			this.requirements = ''
			this.hasVin = false
			this.vin = ''
			this.brand= {
				cn_name: null,
                id:null,
			}
			this.images = []
			uni.removeStorageSync('enquiryParams')
		},
		setOptions(data, type) {
			this.requirements = data.accessoryName
			this.goodsTypes[0].checked = false
			this.goodsTypes[3].checked = true
			this.hasVin = true
			this.vin = data.vin
			this.brand.cn_name= data.brand
			this.onBranchClick(data.brand)
			let list1 = data.images.split(',').filter(item => item != '')
			this.images = list1.map((item) => {
				return { url: item }
			})		
			if (type) {
				uni.removeStorageSync('cyt')
			}

		},
		onQualityChange(e) {
			console.log(e)
			e.detail.value
			this.goodsTypes.forEach(o => {
				o.checked = e.detail.value.indexOf(o.value) >= 0
			})
		},
		onVinInput(e) {
			console.log(e)
			this.vinResult.vin = e.detail.value.trim().toUpperCase()
		},
		async hasMobile() {
			console.log("check mobile", this.userInfo)
			if (this._hasMobile(this.userInfo)) return true
			var user = await this.getUser()
			console.log("userInfo not have mobile", user)
			return this._hasMobile(user)
		},
		_hasMobile(user) {
			return user && !!user.mobile && !!user.nickname
		},
		async checkShopInfo() {
			if (app.globalData.signing === true) { //check sign result
				console.log("check shop")
				var data = uni.getStorageSync("enquiry")
				Object.assign(this.$data, data)
				app.globalData.signing = false
				if (this.isSigned) { //登录成功跳转
					var hasMobile = await this.hasMobile()
					if (!hasMobile) {
						this.regist()
					} else {
						const registed = await this.checkRegist()
						console.log("sign back check regist")
						if (registed) {
							this.addOrder()
						} else {
							this.regist()
						}
					}
				}
			} else if (app.globalData.registing === true) {
				console.log("regist back check")
				app.globalData.registing = false
				var hasMobile = await this.hasMobile()
				if (hasMobile) {
					const registed = await this.checkRegist()
					if (registed) {
						this.addOrder()
					}
				}
			}
		},
		regist() {
			app.globalData.registing = true
			uni.navigateTo({
				url: '/uni_modules/uni-id-pages/pages/userinfo/regist'
			})
		},

		async checkRegist() {
			console.log("check regist", this.registed)
			var shop = app.globalData.shop
			if (!shop) {
				shop = await this.getShop()
			}
			console.log("shop", shop)
			this.registed = shop && !!shop.city_code && !!shop.name && !!shop.address && !!shop.shop_id
			if (this.registed) {
				app.globalData.shop = shop
			}
			return this.registed
		},
		async getUser() {
			let res = await uniCloud.databaseForJQL().collection("uni-id-users")
				.where('_id=="' + this.userInfo._id + '"')
				.field('mobile,nickname,username,email,avatar_file')
				.get()
			console.log("cloud res", res)
			if (res.errCode !== 0) {
				// uni.showModal({
				// 	title: '错误信息',
				// 	content: '读取门店信息失败，请重试',
				// 	showCancel: false
				// })
				return null
			}
			return res.data.length > 0 ? res.data[0] : null
		},
		async getShop() {
			let res = await uniCloud.databaseForJQL().collection("zgj-shop")
				.where('user_id=="' + this.userInfo._id + '"')
				.get()
			console.log("cloud res", res)
			if (res.errCode !== 0) {
				uni.showModal({
					title: '错误信息',
					content: '读取门店信息失败，请重试',
					showCancel: false
				})
				return null
			}
			return res.data.length > 0 ? res.data[0] : null
		},
		onvinclick() {
			console.log("click")
			if (this.hasVin) {
				this.showVin(false)
			} else {
				this.chooseAndUploadVinFile()
			}

		},
		onvinconfirm() {
			if (!this.vinResult.vin) {
				this.phVin = "请输入VIN码"
				return
			}
			if (!this.brand) return
			this.hasVin = true
			this.vin = this.vinResult.vin
			this.vinImg = this.vinResult.vinImg
			this.$refs.vinpopup.close()
			this.showRecord = true
			console.log("this.brand", this.brand)
		},
		onvincancel() {
			this.hasVin = false
			this.vinResult = {
				vin: '',
				vinImg: ''
			}
			this.vin = ''
			this.brand = null
			this.vinImg = ''
			this.$refs.vinpopup.close()
			this.showRecord = true
			this.chooseAndUploadVinFile()
		},
		onbrand() {
			uni.navigateTo({
				url: '/uni_modules/zgj-pages/pages/vechilebrand/vechilebrand?brand=' + this.vinResult.brand
			})
		},
		onBranchClick(data) {
			this.$http.get('/web/ai/brands', {}, (res) => {
			this.brand.id = res.brands.filter(item => data.includes(item.cn_name))[0].id
			})
		},
		async chooseAndUploadVinFile() {
			uniCloud.chooseAndUploadFile({
				type: 'image',
				count: 1,
				sizeType: ['compressed'],
				onChooseFile: e => {
					console.log("choose file", e)
					uni.showLoading({
						title: '上传中'
					})
				},
				success: e => {
					uni.hideLoading()
					console.log("uploaded:", e)
					this.vinImg = "https://env-00jxhjo1f70q.normal.cloudstatic.cn/" + e.tempFiles[0].cloudPath
					this.vinResult = {
						vin: "",
						vinImg: this.vinImg
					}
					this.showVin(true)
				},
				fail(e) {
					uni.hideLoading()
					console.log(e)
					if (e.errMsg !== 'chooseAndUploadFile:fail cancel') {
						uni.showModal({
							content: '上传失败' + e.errMsg
						})
						// uni.showToast({
						// 	title: '上传失败'+e.errMsg,
						// 	icon: 'none'
						// });
					}
				},
				complete() { }
			});
		},
		showVin(parseVin) {
			this.phVin = ''
			this.showRecord = false
			this.$refs.vinpopup.open()
			if (parseVin) {
				this.$http.post('/web/ai/vin', {
					url: this.vinImg
				}, (resp) => {
					console.log("vin:", resp)
					this.vinResult.vin = resp.vin
					if (resp.brand_id) {
						this.brand = {
							id: resp.brand_id,
							cn_name: resp.brand_name,
							images: resp.images
						}
					} else {
						this.brand = null
					}
				})
			}
		},
		sendSound(e) {
			console.log('voice uploaded!', e)
			var data = {
				url: e.url,
				cuid: uni.getDeviceInfo().deviceId
			}
			if (e.lan > 0) {
				data.lan = e.lan
			}
			this.$http.post('/web/ai/voice2text', data, (resp) => {
				if (resp) {
					this.voiceInfo = e
					this.hasVoice = true
					this.requirements = resp
				}
			})
		},
		removeSound() {
			uni.showActionSheet({
				itemList: ["清除"],
				success: (res) => {
					console.log(res)
					this.requirements = ""
					this.hasVoice = false
					this.voiceInfo = null
				}
			})
		},
		signIn() {
			uni.setStorageSync("enquiry", this.$data)
			app.globalData.signing = true
			app.globalData.redirectUrl = '/pages/enquiry/enquiry'
			console.log("siging:", app.globalData.signing)
			uni.navigateTo({
				url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
			})
		},
		showError(err) {
			uni.showModal({
				content: err,
				showCancel: false
			})
		},
		validateOrder() {
			console.log(this.$data, this.images)
			var qualities = this.goodsTypes.filter(o => o.checked)
			if (qualities.length === 0) {
				this.showError('请选择配件品质')
				return
			}
			this.qualityString = qualities.map(o => o.value).join()
			console.log("qualities", qualities, this.qualityString)
			if (!this.vin) {
				this.showError('请上传VIN图片或输入VIN码')
				return
			}
			if (!this.brand) {
				this.showError('请选择汽车品牌')
				return
			}
			if (!this.requirements) {
				this.showError('请输入配件需求')
				return
			}
			this.photos = this.images.map(o => o.url)
			app.globalData.order = {
				photos: this.photos,
				brand_id: this.brand.id,
				brand: this.brand.cn_name,
				vin: this.vin,
				vin_pic: this.vinImg,
				requirements: this.requirements,
				quality: this.qualityString
			}
			if (this.voiceInfo) {
				app.globalData.order.audio_url = this.voiceInfo.url
				app.globalData.order.audio_time = this.voiceInfo.time
			}
			if (this.photos.length > 0) {
				app.globalData.order.pics = this.photos.join()
			}
			return true
		},
		openDescription() {
			uni.navigateTo({
				url: '/uni_modules/uni-feedback/pages/product-description/product-description'
			})
		},
		async onorder() {
			console.log("checklogin...", this.userInfo, this.registed)
			if (!this.validateOrder()) {
				return
			}
			if (!this.isSigned) {
				this.signIn()
			} else if (!this.registed) {
				console.log("not regist")
				this.regist()
			} else {
				var hasMobile = await this.hasMobile()
				console.log("check mobile", hasMobile)
				if (!hasMobile) {
					this.regist()
				} else {
					this.addOrder()
				}
			}
		},
		initOrder() {
			app.globalData.order = null
			this.requirements = ''
			this.showRecord = true
			this.hasVin = false
			this.hasVoice = false
			this.vinImg = ''
			this.vin = ''
			this.brand = null
			this.photos = []
			this.images = []
			this.vinResult = {
				vin: '',
				brand: '',
				id: null,
				vinImg: ''
			}
			this.goodsTypes.forEach(o => o.checked = true)
			this.voiceInfo = null
			this.qualityString = "1,2,3,4"
		},
		subsribe() {
			uni.requestSubscribeMessage({
				tmplIds: [
					"qXqSz5dTr6S67VmfIz_o4R0FkNZnwM1kp5a6Q4XOGbQ",
					"wSGuPQRBsw8GJYVm7wttEtfuZFEGrs7xolyNIaFnWZs",
					"vY_9n--pLwOn3Dfj0FdG1SB5c5UYfHLRV_sSaquk2fA"
				], // 改成你的小程序订阅消息模板id
				success: () => {
					uni.showToast({
						title: "订阅成功",
						icon: "none"
					})
				},
				fail: (res) => {
					console.log("sub fail", res)
				},
				complete: () => {
					uni.navigateTo({
						url: '/uni_modules/zgj-pages/pages/orders/orders'
					})

				}
			});
		},
		addOrder() {

			console.log(app.globalData.shop)
			var shop = app.globalData.shop
			app.globalData.order.shop_id = shop.shop_id
			app.globalData.order.shop_name = shop.name
			app.globalData.order.region = shop.region
			app.globalData.order.prov_id = shop.prov_code
			app.globalData.order.city_id = shop.city_code
			app.globalData.order.county_id = shop.area_code
			app.globalData.order.address = shop.address
			app.globalData.order.user_id = this.userInfo._id
			app.globalData.order.phone = this.userInfo.mobile
			app.globalData.order.contact = this.userInfo.nickname
			app.globalData.order.prefix = this.$config.prefix
			this.$http.post('/web/ai/create_order', app.globalData.order, (res) => {
				this.initOrder()
				this.subsribe()
			}, null, false)
		}
	}
}
</script>

<style lang="scss">
/* #ifndef APP-NVUE */
page {
	display: flex;
	flex-direction: column;
	box-sizing: border-box;
	min-height: 100%;
	height: auto;
}

view {
	font-size: 14px;
	line-height: inherit;
}

/* #endif */
.zgj-car-container {
	background-color: #fff;
	width: 100%;
	height: 200rpx;
	box-sizing: border-box;
	border: 1px solid $uni-border-color;
}

.zgj-vin-big {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: row;
	justify-content: center;
	align-items: center;
}

.zgj-vin-has {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	padding: 10px;
	box-sizing: border-box;

}

.zgj-vin-big .vinimg {
	width: 120px;
	height: 180rpx;
	margin-right: 10px;
}

.zgj-vin-big .zgj-brand {
	display: flex;
	flex-direction: column;
}

.zgj-part-container {
	background-color: #fff;
	width: 100%;
	height: 240rpx;
	padding: 8px;
	box-sizing: border-box;
	border: 1px solid $uni-border-color;
	position: relative;
}

.zgj-part-input {
	width: 100%;
	height: 140rpx;
}

.zgj-goodstype-container {
	margin-top: 4px;
	background-color: $uni-bg-color;
	padding-bottom: 12px;
}

.zgj-goodstype {
	margin-left: 10px;
}

.zgj-part-image-container {
	margin-top: 9px;
	background-color: #fff;
	padding: 10px;
	box-sizing: border-box;
}


.zgj-popup-content {
	background-color: #fff;
	width: 100vw;
	// height: 300px;
	padding: 15px;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}

.zgj-popup-content .vinimg {
	width: 100%;
	height: 200px;
}

.zgj-popup-content .brand {
	width: 40px;
	height: 40px;
	margin-right: 10px;
}

.zgj-popup-content .vechile-brand {
	display: flex;
	justify-content: center;
	align-items: center;
}

.zgj-margin-bottom {
	margin-bottom: 10px;
}

.zgj-vin-brands {
	width: 100%;
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
}

.zgj-vin {
	width: 100%;
	height: 40px;
	font-size: 24px;
	padding-left: 10px;
	border: 1px solid $uni-border-color;
	box-sizing: border-box;
}

.part-box {
	background-color: #ffffff;
	padding: 0 30rpx 170rpx;
}

.foot-btns {
	position: fixed;
	bottom: 0;
	left: 0;
	z-index: 999;
	width: 100%;
	height: 170rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	box-sizing: border-box;
	justify-content: space-around;
	padding: 0 20rpx;

	.shuomin {
		background-color: rgb(245, 245, 245);
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		text-align: center;
		width: 250rpx;
		height: 90rpx;
		border-radius: 10rpx;
		border: 1px solid #dad3d3;
	}

	.collect {
		width: 260rpx;
		height: 90rpx;
		border-radius: 20px;
		background: #FFFFFF;
		border: 1px solid #C4171E;
		font-size: 32rpx;
		color: #000000;

		.active {
			color: #C4171E;
		}
	}

	.phone {
		width: 390rpx;
		height: 90rpx;
		border-radius: 10rpx;
		background: #C4171E;
		font-size: 32rpx;
		color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
	}
}
</style>